package com.aloda.ai;

import com.aloda.ai.anno.AiPlatformConfig;
import com.aloda.constant.ErrorCode;
import com.aloda.dto.AiGenerateResultDTO;
import com.aloda.dto.AiMessageDTO;
import com.aloda.dto.FlowableData;
import com.aloda.enums.AiPlatformEnum;
import com.aloda.exception.BaseException;
import io.reactivex.Flowable;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * AI平台策略执行器
 */
@Service
public class AiPlatformTypeExecutor {

    // 平台策略列表
    @Resource
    private List<AiPlatform> aiPlatformList;

    /**
     * 同步调用AI服务
     * @param aiMessageDTO AI消息dto
     * @return AiGenerateResultDTO
     * @throws Exception 应用配置有误，未找到匹配的策略
     */
    public AiGenerateResultDTO doSyncRequest(AiMessageDTO aiMessageDTO) throws Exception {
        AiPlatformEnum aiPlatform = aiMessageDTO.getAiPlatform();
        if (aiPlatform == null) {
            throw new BaseException(ErrorCode.SYSTEM_ERROR.getCode(), "配置有误，未找到匹配的策略");
        }
        for (AiPlatform aiManager : aiPlatformList) {
            if (aiManager.getClass().isAnnotationPresent(AiPlatformConfig.class)) {
                AiPlatformConfig aiPlatformConfig = aiManager.getClass().getAnnotation(AiPlatformConfig.class);
                if (aiPlatformConfig.platformType() == aiPlatform) {
                    return aiManager.doSyncRequest(aiMessageDTO);
                }
            }
        }
        throw new BaseException(ErrorCode.SYSTEM_ERROR.getCode(), "配置有误，未找到匹配的策略");
    }

    /**
     * 处理流式调用请求
     * @param aiMessageDTO AI消息dto
     * @return Flowable<FlowableData> 返回流式请求结果
     */
    public Flowable<FlowableData> doStreamRequest(AiMessageDTO aiMessageDTO) {
        AiPlatformEnum aiPlatform = aiMessageDTO.getAiPlatform();
        if (aiPlatform == null) {
            throw new BaseException(ErrorCode.SYSTEM_ERROR.getCode(), "配置有误，未找到匹配的策略");
        }
        for (AiPlatform aiManager : aiPlatformList) {
            if (aiManager.getClass().isAnnotationPresent(AiPlatformConfig.class)) {
                AiPlatformConfig aiPlatformConfig = aiManager.getClass().getAnnotation(AiPlatformConfig.class);
                if (aiPlatformConfig.platformType() == aiPlatform) {
                    return aiManager.doStreamRequest(aiMessageDTO);
                }
            }
        }
        throw new BaseException(ErrorCode.SYSTEM_ERROR.getCode(), "配置有误，未找到匹配的策略");
    }
}
